import {
  Table,
  Input,
  Button,
  Popconfirm,
  Form,
  Col,
  InputNumber,
  Select,
  Divider,
  Upload,
} from 'antd';
import React, { Component } from 'react';
import BaseComponent from '@/components/BaseComponent';
import styles from './index.less';
import styled from 'styled-components';
import { njzdImgPrefixUrl } from '@/defaultSettings';
import EsophagusView from "@/components/EsophagusView";
import CardiaView from "@/components/CardiaView";
import StomachView from "@/components/StomachView";
import ReportCard from "@/components/ReportCard";


const { Option } = Select;

const FormItemBox = styled.div`
  display: flex;
  align-items: center;
`;

const ThumbnailBox = styled.div`
  width: 103px;
  height: 103px;
  display: flex;
  align-items: center;
  margin-top: 8px;

  .thumbnailImage {
    width: 103px;
    height: 103px;
  }

  .delBtn {
    margin-left: 16px;
  }
`;

/**
 * 内镜详情
 */
@Form.create()
class EndoscopeDetail extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      form: [],
      data: [
        {
          id: this.generateId(),
        },
      ],
      columns: [],
      // 报告单存放地址
      reportFilePath: '',
      // 报告单url访问地址
      reportFileUrl: '',
      // 病理报告单url访问地址
      blReportFileUrl: '',
      // 病理报告单存放地址
      blReportFilePath: '',
      // 是否正在上传
      isUploading:false
    };
  }

  componentDidMount() {
    this.getColumns();
    const { record } = this.props;
    const { reportFileUrl, blReportFileUrl } = record;
    this.setState({
      reportFileUrl,
      blReportFileUrl,
    });
  }

  getColumns = () => {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    let cs = [
      {
        title: '病变位于(1)至(2)',
        render: (text, record, index) => {
          const { lesionLocationStart, lesionLocationEnd } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`lesionLocationStart-${index}`, {
                  initialValue: lesionLocationStart,
                })(
                  <Select
                    placeholder="请选择"
                    style={{
                      width: '120px',
                      marginRight: '8px',
                    }}
                  >
                    <Option value={1}>头部</Option>
                    <Option value={2}>身体</Option>
                  </Select>
                )}
              </Form.Item>
              至
              <Form.Item>
                {getFieldDecorator(`lesionLocationEnd-${index}`, {
                  initialValue: lesionLocationEnd,
                })(
                  <Select placeholder="请选择" style={{ width: '120px', marginLeft: '8px' }}>
                    <Option value={1}>头部</Option>
                    <Option value={2}>身体</Option>
                  </Select>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '距离(CM)',
        render: (text, record, index) => {
          const { distanceStart, distanceEnd } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`distanceStart-${index}`, {
                  initialValue: distanceStart,
                })(<InputNumber style={{ width: '120px', marginRight: '8px' }} />)}
              </Form.Item>
              至
              <Form.Item>
                {getFieldDecorator(`distanceEnd-${index}`, {
                  initialValue: distanceEnd,
                })(<InputNumber style={{ width: '120px', marginLeft: '8px' }} />)}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '方向',
        render: (text, record, index) => {
          const { direction } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`direction-${index}`, {
                  initialValue: direction,
                })(
                  <Select placeholder="请选择" style={{ width: '120px' }}>
                    <Option value={1}>头部</Option>
                    <Option value={2}>身体</Option>
                  </Select>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '请选择分类',
        render: (text, record, index) => {
          const { classification } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(
                  `classification-${index}`,
                  {}
                )(
                  <Select placeholder="请选择分类" style={{ width: '120px' }}>
                    <Option value={1}>头部</Option>
                    <Option value={2}>身体</Option>
                  </Select>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '操作',
        width: 200,
        // fixed: 'right',
        // dataIndex: 'operation',
        render: (text, record, index) => {
          return (
            <div>
              <Button
                style={{ marginRight: '8px' }}
                type="primary"
                size={'small'}
                onClick={() => this.handleAdd()}
              >
                添加病变
              </Button>
              <Popconfirm
                title="确定执行当前操作吗?"
                onConfirm={() => this.handleDelete(record.id)}
              >
                <Button type="danger" size={'small'}>
                  删除病变
                </Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    this.setState({
      columns: cs,
    });
  };

  handleDelete = id => {
    const data = [...this.state.data];
    if (data.length === 1) {
      this.errorMessage('至少保留一行！');
      return;
    }
    this.setState({
      data: data.filter(item => item.id !== id),
    });
  };

  handleAdd = () => {
    const { data } = this.state;
    const newData = {
      id: this.generateId(),
    };
    this.setState({
      data: [...data, newData],
    });
  };

  render() {
    const { record, sg, bm, w, disabled = false } = this.props;
    const { isShowSgDetail, isShowBmDetail, isShowWDetail } = record;
    return (
      <div className={styles.editableTable}>
        {/*食管*/}
        {isShowSgDetail == 1 ? (
          <EsophagusView
            disabled={disabled}
            sg={sg}
            wrappedComponentRef={esophagusview => (this.esophagusview = esophagusview)}
          ></EsophagusView>
        ) : null}
        {/*贲门*/}
        {isShowBmDetail == 1 ? (
          <CardiaView
            disabled={disabled}
            bm={bm}
            wrappedComponentRef={cardiaview => (this.cardiaview = cardiaview)}
          ></CardiaView>
        ) : null}
        {/*胃*/}
        {isShowWDetail == 1 ? (
          <StomachView
            disabled={disabled}
            w={w}
            wrappedComponentRef={stomachview => (this.stomachview = stomachview)}
          ></StomachView>
        ) : null}
        {/*内镜报告单*/}
        <ReportCard
          disabled={disabled}
          title={'内镜报告单'}
          emptyMsg={'暂无内镜报告单,请上传内镜报告单'}
          uploadBtnLabel={'上传内镜报告单'}
          fileUrl={this.state.reportFileUrl}
          isUploading={this.state.isUploading}
          beforeUpload={this.handleUploadBefore}
          onChange={this.handleUploadChange}
          onDelClick={this.handleDelImage}
        ></ReportCard>

        {/*病理报告单*/}
        <ReportCard
          disabled={disabled}
          title={'病理报告单'}
          emptyMsg={'暂无病理报告单,请上传病理报告单'}
          uploadBtnLabel={'上传病理报告单'}
          fileUrl={this.state.blReportFileUrl}
          isUploading={this.state.isUploading}
          beforeUpload={this.handleUploadBefore}
          onChange={this.handleBlUploadChange}
          onDelClick={this.handleDelBlImage}
        ></ReportCard>
      </div>
    );
  }

  handleUploadBefore = (file, fileList) => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage('正在上传...');
    });
    return true;
  };

  handleUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => {}
      );
    }
    if (info.file.status === 'done') {
      const response = info.file.response;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;
      this.setState({
        reportFilePath: filePath,
        reportFileUrl: url,
        isUploading: false,
      });
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };

  handleBlUploadChange = ({ info }) => {
    if (info.file.status !== 'uploading') {
      this.setState(
        {
          fileList: info.fileList,
        },
        () => {}
      );
    }
    if (info.file.status === 'done') {
      const response = info.file.response;
      const {
        data: { filePath, originalFilename },
      } = response;
      const arr = filePath.split('/');
      // 文件前缀
      const prefix = arr[arr.length - 2];
      const url = `${prefix}/${originalFilename}`;
      this.setState({
        blReportFilePath: filePath,
        blReportFileUrl: url,
        isUploading: false,
      });
      if (this.hide) {
        this.hide();
      }
      this.successMessage('上传成功');
    } else if (info.file.status === 'error') {
      this.errorMessage('文件上传出错,请联系管理员');
    }
  };

  handleDelImage = () => {
    this.setState({
      reportFileUrl: '',
      reportFilePath: '',
    });
  };

  handleDelBlImage = () => {
    this.setState({
      blReportFileUrl: '',
      blReportFilePath: '',
    });
  };
}

export default EndoscopeDetail;
